package com.hxkcloud.patient.alarm;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hxkcloud.patient.R;
import com.hxkcloud.patient.activitys.UserFragmentActivity;
import com.hxkcloud.patient.config.Constant;
//import com.umeng.analytics.MobclickAgent;

import java.util.List;

import cn.jpush.android.api.JPushInterface;

/**
 * Created by william_sun on 2016-08-18.
 * Description:Alarm Clock alarm alert: pops visible indicator and plays alarm
 * tone. This activity is the full screen version which shows over the lock
 * screen with the wallpaper as the background.
 * 锁屏全屏展示的activity
 */
public class AlarmAlertFullScreen extends Activity {
    // These defaults must match the values in res/xml/settings.xml
    private static final String DEFAULT_SNOOZE = "10";
    private static final String DEFAULT_VOLUME_BEHAVIOR = "2";
    protected static final String SCREEN_OFF = "screen_off";
    static final String KEY_ALARM_SNOOZE =
            "snooze_duration";
    static final String KEY_VOLUME_BEHAVIOR =
            "volume_button_setting";
    protected Alarm mAlarm;
    private int mVolumeBehavior;

    protected int screenWidth;

    // Receives the ALARM_KILLED action from the AlarmKlaxon,
    // and also ALARM_SNOOZE_ACTION / ALARM_DISMISS_ACTION from other applications
    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(Constant.ALARM_SNOOZE_ACTION)) {
                snooze();
            } else if (action.equals(Constant.ALARM_DISMISS_ACTION)) {
                dismiss(false);
            } else {
                Alarm alarm = intent.getParcelableExtra(Alarms.ALARM_INTENT_EXTRA);
                if (alarm != null && mAlarm.id == alarm.id) {
                    dismiss(true);
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mAlarm = getIntent().getParcelableExtra(Alarms.ALARM_INTENT_EXTRA);
        //sign changed by reason
        Alarm dbAlarm = Alarms.getAlarm(getContentResolver(), mAlarm.id);
        if (dbAlarm != null) {
            mAlarm = dbAlarm;
        }

        // Get the volume/camera button behavior setting
        final String vol =
                PreferenceManager.getDefaultSharedPreferences(this)
                        .getString(KEY_VOLUME_BEHAVIOR,
                                DEFAULT_VOLUME_BEHAVIOR);
        mVolumeBehavior = Integer.parseInt(vol);

        requestWindowFeature(android.view.Window.FEATURE_NO_TITLE);

        final Window win = getWindow();
        win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
                | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
        // Turn on the screen unless we are being launched from the AlarmAlert
        // subclass.
        if (!getIntent().getBooleanExtra(SCREEN_OFF, false)) {
            win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
                    | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
                    | WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON);
        }

        updateLayout();

        // Register to get the alarm killed/snooze/dismiss intent.
        IntentFilter filter = new IntentFilter(Alarms.ALARM_KILLED);
        filter.addAction(Constant.ALARM_SNOOZE_ACTION);
        filter.addAction(Constant.ALARM_DISMISS_ACTION);
        registerReceiver(mReceiver, filter);
    }

    //设置标题（时间）
    private void setTitle() {
        String h = mAlarm.hour + "";
        if (mAlarm.hour < 10) {
            h = "0" + h;
        }
        String m = mAlarm.minutes + "";
        if (mAlarm.minutes < 10) {
            m = "0" + m;
        }
        String time = h + ":" + m;
        TextView title = (TextView) findViewById(R.id.tv_alarm_time);
        title.setText(time);
    }

    private void updateLayout() {
        LayoutInflater inflater = LayoutInflater.from(this);

        setContentView(inflater.inflate(R.layout.alarm_alart, null));

        DisplayMetrics dm = new DisplayMetrics();
        this.getWindowManager().getDefaultDisplay().getMetrics(dm);
        screenWidth = dm.widthPixels;

        LinearLayout ll_alarm = (LinearLayout) findViewById(R.id.ll_alarm);
        LinearLayout.LayoutParams lp_ll = new LinearLayout.LayoutParams(screenWidth * 4 / 5, LinearLayout.LayoutParams.WRAP_CONTENT);
        ll_alarm.setLayoutParams(lp_ll);
        LinearLayout.LayoutParams lp_delay = new LinearLayout.LayoutParams((screenWidth * 2 / 5) - 1, LinearLayout.LayoutParams.WRAP_CONTENT);
        LinearLayout.LayoutParams lp_see = new LinearLayout.LayoutParams((screenWidth * 2 / 5) - 1, LinearLayout.LayoutParams.WRAP_CONTENT);
        lp_see.leftMargin = 2;

        //delay,snooze延迟
        Button bt_delay = (Button) findViewById(R.id.bt_alarm_delay);
//        bt_delay.requestFocus();
        bt_delay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                snooze();
            }
        });
        bt_delay.setLayoutParams(lp_delay);

        //查看详情
        Button bt_see = (Button) findViewById(R.id.bt_alarm_see);
        bt_see.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss(false);

                //还需判断是否打开应用
//                if (!isRunningForeground(AlarmAlertFullScreen.this)) {
//                com.yjhcloud.patient.ActivityManager.getInstance().removeAllActivity();
                Intent mIntent = new Intent(AlarmAlertFullScreen.this, UserFragmentActivity.class);
//                mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
//                mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
//                mIntent.setClassName("com.yjhcloud.patient", "com.yjhcloud.patient.activitys.UserFragmentActivity");
                mIntent.putExtra("page", 3);
                mIntent.putExtra("alarm","alarm");
                startActivity(mIntent);
//                    Intent iMain = new Intent(AlarmAlertFullScreen.this, StartActivity.class);
//                    startActivity(iMain);
//                    finish();
//                } else {
////                    Toast.makeText(AlarmAlertFullScreen.this, "yes",
////                            Toast.LENGTH_LONG).show();
//                }
            }
        });
        bt_see.setLayoutParams(lp_see);

        setTitle();
    }

    private boolean isRunningForeground(Context context) {
        ActivityManager mActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> taskInfo = mActivityManager.getRunningTasks(1);
        String mCurrentPackageName = "com.yjhcloud.patient";
        if (taskInfo.size() > 0) {
            String mTopPackageName = taskInfo.get(0).topActivity.getPackageName();
            // Log.i(TAG, "mTopPackageName : " + mTopPackageName);
            if (mCurrentPackageName.equals(mTopPackageName)) {
                return true;
            }
        }
        return false;
    }

    // Attempt to snooze this alert.
    private void snooze() {
        long snoozeTime = System.currentTimeMillis()
                + (1000 * 60 * 10);
        //设置延迟闹钟
        Alarms.saveSnoozeAlert(AlarmAlertFullScreen.this, mAlarm.id,
                snoozeTime);

//        // Get the display time for the snooze and update the notification.
//        Calendar c = Calendar.getInstance();
//        c.setTimeInMillis(snoozeTime);
//        // Append (snoozed) to the label.
//        String label = mAlarm.getLabelOrDefault(this);
//        label = getString(R.string.alarm_notify_snooze_label, label);
//        // Notify the user that the alarm has been snoozed.
//        Intent cancelSnooze = new Intent(this, AlarmReceiver.class);
//        cancelSnooze.setAction(Alarms.CANCEL_SNOOZE);
//        cancelSnooze.putExtra(Alarms.ALARM_ID, mAlarm.id);
//        PendingIntent broadcast =
//                PendingIntent.getBroadcast(this, mAlarm.id, cancelSnooze, 0);
//        NotificationManager nm = getNotificationManager();
//        Notification n = new Notification(R.drawable.stat_notify_alarm,
//                label, 0);
//        n.setLatestEventInfo(this, label,
//                getString(R.string.alarm_notify_snooze_text,
//                        Alarms.formatTime(this, c)), broadcast);
//        n.flags |= Notification.FLAG_AUTO_CANCEL
//                | Notification.FLAG_ONGOING_EVENT;
//        nm.notify(mAlarm.id, n);

        Toast.makeText(AlarmAlertFullScreen.this, R.string.delay10minute,
                Toast.LENGTH_LONG).show();
        Intent intent = new Intent(Constant.ALARM_ALERT_ACTION);
        intent.setPackage(this.getPackageName());
        stopService(intent);
        finish();
    }

    private NotificationManager getNotificationManager() {
        return (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    }

    // Dismiss the alarm.不懂还需测试
    private void dismiss(boolean killed) {
        // The service told us that the alarm has been killed, do not modify
        // the notification or stop the service.
        if (!killed) {
            // Cancel the notification and stop playing the alarm
            NotificationManager nm = getNotificationManager();
            nm.cancel(mAlarm.id);
            Intent intent = new Intent(Constant.ALARM_ALERT_ACTION);
            intent.setPackage(this.getPackageName());
            stopService(intent);
        }
        finish();
    }

    /**
     * this is called when a second alarm is triggered while a
     * previous alert window is still active.
     */
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        Log.v("wangxianminggood", "AlarmAlert.OnNewIntent()");

        mAlarm = intent.getParcelableExtra(Alarms.ALARM_INTENT_EXTRA);

        setTitle();
    }

    @Override
    protected void onResume() {
        super.onResume();
//        MobclickAgent.onResume(this);
        JPushInterface.onResume(this);
        // If the alarm was deleted at some point, disable snooze.
//        if (Alarms.getAlarm(getContentResolver(), mAlarm.id) == null) {
//            Button snooze = (Button) findViewById(R.id.snooze);
//            snooze.setEnabled(false);
//        }
    }

    @Override
    protected void onPause() {
        super.onPause();
//        MobclickAgent.onPause(this);
        JPushInterface.onPause(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.v("wangxianminggood", "AlarmAlert.onDestroy()");
        // No longer care about the alarm being killed.
        unregisterReceiver(mReceiver);
    }

    //mVolumeBehavior如何来的
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        // Do this on key down to handle a few of the system keys.
        boolean up = event.getAction() == KeyEvent.ACTION_UP;
        switch (event.getKeyCode()) {
            // Volume keys and camera keys dismiss the alarm
            case KeyEvent.KEYCODE_VOLUME_UP:
            case KeyEvent.KEYCODE_VOLUME_DOWN:
            case KeyEvent.KEYCODE_CAMERA:
            case KeyEvent.KEYCODE_FOCUS:
                if (up) {
                    switch (mVolumeBehavior) {
                        case 1:
                            snooze();
                            break;

                        case 2:
                            dismiss(false);
                            break;

                        default:
                            break;
                    }
                }
                return true;
            default:
                break;
        }
        return super.dispatchKeyEvent(event);
    }

    @Override
    public void onBackPressed() {
        // Don't allow back to dismiss. This method is overriden by AlarmAlert
        // so that the dialog is dismissed.
        return;
    }
}
